import axios from 'axios'
import { MessageBox, Message } from 'element-ui'


// create an axios instance
const service = axios.create({
  baseURL: 'api', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Content-Type'] = 'application/json';
    config.headers['Cache-Control'] = 'no-cache'
    config.headers['Pragma'] = 'no-cache'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === '1') {
      MessageBox.alert(res.message, '提示', {
        type: 'error'
      });
      return Promise.reject(res.data || res.message || 'error')
    }
    return res;
  },
  error => {
      let msg = null
      console.log('err' + error); // for debug
      if (error.message.indexOf('timeout') !== -1) {
          msg = '请求超时'
      }
      Message({
          message: msg || error.message,
          type: 'error',
          duration: 5 * 1000
      })
      return Promise.reject(error)
  }
)

export default service
